import { BluetoothPrinterService } from './../../services/bluetooth-printer.service';
import { Component, OnInit } from '@angular/core';
import { ModalController, ToastController, LoadingController, ViewDidEnter, ViewWillEnter, ViewDidLeave } from '@ionic/angular';
import { Global } from 'src/app/services/global.service';
import { LocalStorage } from 'src/app/services/local-storage.service';

@Component({
	selector: 'app-select-device',
	templateUrl: './select-device.page.html',
	styleUrls: ['./select-device.page.scss'],
})
export class SelectDevicePage implements ViewWillEnter, ViewDidLeave {

	isBluetoothEnabled: boolean;

	uuids = [];

	devices = [];

	interval: any;

	isScanStart = false;

	connectedDevice: any;

	constructor(
		private modalCtrl: ModalController,
		private toastCtrl: ToastController,
		private bps: BluetoothPrinterService,
		private loadingCtrl: LoadingController,
		private global: Global
	) {
	}

	ionViewWillEnter() {
		this.interval = setInterval(async () => {
			this.isBluetoothEnabled = await this.bps.isEnabled();
			if (this.isBluetoothEnabled && !this.isScanStart) {
				await this.searchDevice()
			}
			this.connectedDevice = this.bps.getDevice();
		}, 500)
	}

	ionViewDidLeave(): void {
		clearInterval(this.interval);
		this.scanStop();
	}

	async enableBluetooth() {
		await this.bps.openBluetoothSetting();
	}

	async searchDevice() {
		this.isScanStart = true;
		this.bps.startScan().subscribe(
			device => {
				if (device.name && this.uuids.indexOf(device.id) < 0) {
					this.uuids.push(device.id);
					this.devices.push(device);
				}
			}
		)
	}

	async scanStop() {
		this.isScanStart = false;
		await this.bps.stopScan();
	}

	async connect(device: any) {
		const loading = await this.loadingCtrl.create({});
		await loading.present();
		this.bps.connect(device.id).subscribe(
			async peripheral => {
				console.log(peripheral)
				await loading.dismiss();
				if (this.bps.isPrinter(peripheral)) {
					this.bps.save(peripheral);
					this.toast(this.translate("CONNECT_SUCCESS"))
				} else {
					this.bps.disconnect(device.id);
					this.toast(this.translate("NOT_A_PRINTER"))
				}
			}
		);
	}

	async dismiss() {
		await this.modalCtrl.dismiss();
	}

	private async toast(message: string) {
		const toast = await this.toastCtrl.create({
			message,
			duration: 3000
		});
		await toast.present();
	}


	translate(key: string) {
		return this.global.translate(key);
	}

}
